/**
 * @fileoverview
 *
 *  Example of configuration section related to datastore
 *  
 *  "datastore": {
 *     "type": "mongodb",
 *     "uri": "uxperf",
 *     "state_collection": "state",
 *     "data_collection_prefix": "datapkgs"
 *   }
 */

var MongoDbDataStore = module.exports = function(cfg) {
  MongoDbDataStore.NDEBUG = cfg['ndebug'];
  MongoDbDataStore.dataCollectionPrefix = cfg['data_collection_prefix'] || 'datapkgs';
  
  MongoDbDataStore.db = db = require('mongojs').connect(cfg['uri'], [cfg['state_collection']]);
  if (!db || !db[cfg['state_collection']]) throw Error('Could not connect to DB');
  
  db[cfg['state_collection']].findOne({}, function(err, res) {
    if (err) throw Error('Could not connect to DB : ' + err);
  });
  
  MongoDbDataStore.collection = null;
  MongoDbDataStore.today = null;
  
  console.log('MongoDB Data Store initialized');
};

MongoDbDataStore.save = function(data, timeOffset, serverTime, clientTime) {
  MongoDbDataStore.NDEBUG || console.log('save - timeOffset: %d, serverTime: %d, clientTime: %d, data: %s', timeOffset, serverTime, clientTime, data);
  
  var serverDate = new Date(serverTime);
  serverDate = [serverDate.getFullYear(), (serverDate.getMonth()<9) ? '0': '', serverDate.getMonth()+1, (serverDate.getDate()<10) ? '0' : '', serverDate.getDate()].join('');
  
  if (MongoDbDataStore.today != serverDate) {
    MongoDbDataStore.NDEBUG || console.log('save - starting with collection %s%s', MongoDbDataStore.dataCollectionPrefix, serverDate);
    MongoDbDataStore.collection = db.collection(MongoDbDataStore.dataCollectionPrefix + serverDate);
    MongoDbDataStore.today = serverDate;
  }
  
  MongoDbDataStore.collection.insert({
    serverTime: serverTime,
    timeOffset: timeOffset,
    clientTime: clientTime,
    data: data
  }, {safe: false});
};

MongoDbDataStore.close = function() {
  MongoDbDataStore.db.close();
};